package com.elder.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.*;
import com.elder.business.mapper.*;
import com.elder.common.core.domain.AjaxResult;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.core.redis.RedisCache;
import com.elder.common.enums.ApplyStatus;
import com.elder.common.enums.BedType;
import com.elder.common.enums.NurseStatus;
import com.elder.common.enums.RoomType;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elder.business.service.IElderlyapartmentService;

/**
 * 公寓信息Service业务层处理
 * 
 * @author zyk
 * @date 2023-11-26
 */
@Service
public class ElderlyapartmentServiceImpl implements IElderlyapartmentService 
{
    @Autowired
    private ElderlyapartmentMapper elderlyapartmentMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private ApartmentRoomInfoMapper apartmentRoomInfoMapper;
    @Autowired
    private ElderlyApartmentBedsMapper elderlyApartmentBedsMapper;
    @Autowired
    private ApartmentDictMapper apartmentDictMapper;
    @Autowired
    private NurseContentMapper nurseContentMapper;
    @Autowired
    private RedisCache redisCache;

    private static final String APARTMENT_INFO_KEY = "ELDER_APARTMENT";
    private static final String APARTMENT_ROOM_PROJECT_KEY = "ROOMANDPROJECT";
    private static final String APARTMENT_ROOM_PROJECT_HX_KEY = "room_project";
    /**
     * 查询公寓信息
     * 
     * @param apartmentId 公寓信息主键
     * @return 公寓信息
     */
    @Override
    public JSONObject selectElderlyapartmentByApartmentId(Long apartmentId)
    {
        Elderlyapartment v = elderlyapartmentMapper.selectElderlyapartmentByApartmentId(apartmentId);
        JSONObject obj = new JSONObject();
        obj.put("apartmentId", StringNewUtils.long2Str(v.getApartmentId()));
        obj.put("apartmentName", v.getApartmentName());
        obj.put("capacity", v.getCapacity());
        obj.put("occupied", v.getOccupied());
        obj.put("phoneNumber", v.getPhoneNumber());
        return obj;
    }

    /**
     * 查询公寓信息列表
     * 
     * @param elderlyapartment 公寓信息
     * @return 公寓信息
     */
    @Override
    public List<JSONObject> selectElderlyapartmentList(Elderlyapartment elderlyapartment)
    {
        redisCache.getCacheMapValue(APARTMENT_INFO_KEY,"elder_apartment");
        List<JSONObject> result = elderlyapartmentMapper.selectElderlyapartmentList(elderlyapartment).stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("apartmentId", StringNewUtils.long2Str(v.getApartmentId()));
            obj.put("apartmentName", v.getApartmentName());
            obj.put("capacity", v.getCapacity());
            obj.put("occupied", v.getOccupied());
            obj.put("phoneNumber", v.getPhoneNumber());
            return obj;
        }).collect(Collectors.toList());

        redisCache.setCacheMapValue(APARTMENT_INFO_KEY,"elder_apartment",result.toString());
        return result;
    }

    /**
     * 新增公寓信息
     * 
     * @param elderlyapartment 公寓信息
     * @return 结果
     */
    @Override
    public int insertElderlyapartment(Elderlyapartment elderlyapartment)
    {
        elderlyapartment.setApartmentId(SnowGenerator.getId());
        return elderlyapartmentMapper.insertElderlyapartment(elderlyapartment);
    }

    /**
     * 修改公寓信息
     * 
     * @param elderlyapartment 公寓信息
     * @return 结果
     */
    @Override
    public int updateElderlyapartment(Elderlyapartment elderlyapartment)
    {
        return elderlyapartmentMapper.updateElderlyapartment(elderlyapartment);
    }

    /**
     * 批量删除公寓信息
     * 
     * @param apartmentIds 需要删除的公寓信息主键
     * @return 结果
     */
    @Override
    public int deleteElderlyapartmentByApartmentIds(Long[] apartmentIds)
    {
        return elderlyapartmentMapper.deleteElderlyapartmentByApartmentIds(apartmentIds);
    }

    /**
     * 删除公寓信息信息
     * 
     * @param apartmentId 公寓信息主键
     * @return 结果
     */
    @Override
    public int deleteElderlyapartmentByApartmentId(Long apartmentId)
    {
        return elderlyapartmentMapper.deleteElderlyapartmentByApartmentId(apartmentId);
    }

    @Override
    public JSONArray getAllElderApartment() {
        redisCache.getCacheMapValue(APARTMENT_INFO_KEY,"elder_apartment");
        List<Elderlyapartment> list = elderlyapartmentMapper.selectElderlyapartmentList(new Elderlyapartment());
        JSONObject obj = null;
        JSONArray result = new JSONArray();
        for(Elderlyapartment dto : list){
            obj = new JSONObject();
            obj.put("apartmentId", StringNewUtils.long2Str(dto.getApartmentId()));
            obj.put("apartmentName",StringNewUtils.isEmpty(dto.getApartmentName())?"":dto.getApartmentName());
            obj.put("capacity", Objects.isNull(dto.getCapacity()) ? "":StringNewUtils.long2Str(dto.getCapacity()));
            obj.put("occupied",Objects.isNull(dto.getOccupied()) ? "":StringNewUtils.long2Str(dto.getOccupied()));
            obj.put("phoneNumber",StringNewUtils.isEmpty(dto.getPhoneNumber())?"":dto.getPhoneNumber());
            result.add(obj);
        }
        redisCache.setCacheMapValue(APARTMENT_INFO_KEY,"elder_apartment",result.toJSONString());
        return result;
    }

    @Override
    public ElderlyStatisticsDTO getApartmentStatistics() {
        ElderlyStatisticsDTO statistics = elderlyInfoMapper.getApartmentStatistics();
        return statistics;
    }

    /***
     * @description 获取banner列表
     * @return TableDataInfo
     * @author zyk
     * @date 2024/2/29 16:28
     */
    @Override
    public TableDataInfo getApartmentBannerList() {
        List<ApartmentBanner> apartmentBannerList = elderlyapartmentMapper.getApartmentBannerList();
        List<JSONObject> list = apartmentBannerList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("bannerId", StringNewUtils.long2Str(v.getBannerId()));
            obj.put("bannerName", v.getBannerName());
            obj.put("bannerUrl", v.getBannerUrl());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo data = new TableDataInfo();
        data.setCode(200);
        data.setRows(list);
        return data;
    }

    /***
     * @description 根据bannerId获取banner信息
     * @param bannerId
     * @return JSONObject
     * @author zyk
     * @date 2024/2/29 16:32
     */
    @Override
    public JSONObject getApartmentBanner(Long bannerId) {
        ApartmentBanner apartmentBanner = elderlyapartmentMapper.getApartmentBanner(bannerId);
        if(Objects.isNull(apartmentBanner)){
            return new JSONObject();
        }
        JSONObject obj = new JSONObject();
        obj.put("bannerId", StringNewUtils.long2Str(apartmentBanner.getBannerId()));
        obj.put("bannerName", apartmentBanner.getBannerName());
        obj.put("bannerUrl", apartmentBanner.getBannerUrl());
        return obj;
    }

    @Override
    public AjaxResult addApartmentBanner(ApartmentBanner banner) {
        banner.setBannerId(SnowGenerator.getId());
        elderlyapartmentMapper.addApartmentBanner(banner);
        return AjaxResult.success();
    }

    /***
     * @description  修改轮播图信息
     * @param banner
     * @return AjaxResult
     * @author zyk
     * @date 2024/2/29 16:41
     */
    @Override
    public AjaxResult updateApartmentBanner(ApartmentBanner banner) {
        elderlyapartmentMapper.updateApartmentBanner(banner);
        return AjaxResult.success();
    }

    /***
     * @description  逻辑删除轮播图
     * @param bannerId
     * @return AjaxResult
     * @author zyk
     * @date 2024/2/29 16:40
     */
    @Override
    public AjaxResult delApartmentBanner(Long bannerId) {
        elderlyapartmentMapper.delApartmentBanner(bannerId);
        return AjaxResult.success();
    }

    @Override
    public JSONObject getElderApartMentRoomBedList() {
//        List<JSONObject> roomTreeList = redisCache.getCacheList("RoomTreeList");
//        if(CollectionUtils.isNotEmpty(roomTreeList)){
//            JSONObject str = new JSONObject();
//            str.put("data",roomTreeList);
//            return str;
//        }
        List<Elderlyapartment> allApartmentInfo = elderlyapartmentMapper.getAllApartmentInfo();
        List<ElderlyApartmentBeds> roomBeds = elderlyApartmentBedsMapper.getAllRoomBeds();
        List<ApartmentRoomInfo> roomIfoList = apartmentRoomInfoMapper.getRoomIfoList();
        Map<Integer, String> map = apartmentDictMapper.getApartmentDictInfo(1).stream().collect(Collectors.toMap(ApartmentDict::getCode, ApartmentDict::getName));

        JSONObject obj = null;
        List<JSONObject> result = new ArrayList<>();
        //封装数据
        for(Elderlyapartment dto : allApartmentInfo){
            obj = new JSONObject();
            obj.put("Id", StringNewUtils.long2Str(dto.getApartmentId()));
            obj.put("name",dto.getApartmentName());
            obj.put("children",roomIfoList.stream().filter(rel ->
                    Objects.equals(rel.getRoomStatus(), RoomType.ROOM_NOT_FULL.getValue()) && Objects.equals(rel.getApartmentId(),dto.getApartmentId())
                    ).map(v->{
                JSONObject room = new JSONObject();
                room.put("Id",StringNewUtils.long2Str(v.getRoomId()));
                room.put("name",map.get(v.getRoomType())+":"+v.getRoomCode()+":"+v.getRoomSex()+":"+v.getRoomDescribe());
                room.put("children",roomBeds.stream().filter(
                        b-> Objects.equals(b.getRoomId(),v.getRoomId()) && Objects.equals(b.getBedStatus(), BedType.BED_FREE.getValue())
                ).map(bed->{
                        JSONObject bedInfo = new JSONObject();
                        bedInfo.put("Id",StringNewUtils.long2Str(bed.getId()));
                        bedInfo.put("name","所剩床位："+bed.getBedCode());
                        return bedInfo;
                    }).collect(Collectors.toList()));
                    return room;
                }).collect(Collectors.toList())
            );
            result.add(obj);
        }
//        redisCache.setCacheList("RoomTreeList",result);
        JSONObject data = new JSONObject();
        data.put("data",result);
        return data;
    }

    /***
     * @description 获取房间 服务项目信息
     * @return JSONObject
     * @author zyk
     * @date 2024/2/29 16:42
     */
    @Override
    public JSONObject getRoomType() {
        JSONObject cacheMapValue = redisCache.getCacheMapValue(APARTMENT_ROOM_PROJECT_KEY, APARTMENT_ROOM_PROJECT_HX_KEY);
        if(Objects.nonNull(cacheMapValue)){
            return cacheMapValue;
        }
        List<ApartmentRoomPrice> priceList = apartmentRoomInfoMapper.getApartmentRoomPriceList(null, ApplyStatus.APPLY_PASS.getValue());
        List<ApartmentDict> apartmentDictInfo = apartmentDictMapper.getApartmentDictInfo(1);
        Map<Integer, String> codeMap = apartmentDictInfo.stream().collect(Collectors.toMap(ApartmentDict::getCode, ApartmentDict::getName));
        List<JSONObject> price = priceList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("roomPriceId", StringNewUtils.long2Str(v.getRoomPriceId()));
            obj.put("roomName", codeMap.get(v.getRoomType()));
            obj.put("roomType",v.getRoomType());
            obj.put("roomPrice", v.getRoomPrice());
            return obj;
        }).collect(Collectors.toList());
        List<NurseContent> contentList = nurseContentMapper.selectNurseContentList(null, NurseStatus.ENABLE.getValue())
                .stream().filter(nurse -> Objects.equals(nurse.getNurseStatus(), 1)).collect(Collectors.toList());

        List<JSONObject> nurse = contentList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("nurseId", StringNewUtils.long2Str(v.getNurseId()));
            obj.put("nurseName", v.getNurseName());
            obj.put("nursePrice", v.getNursePrice());
            return obj;
        }).collect(Collectors.toList());

        JSONObject data = new JSONObject();
        data.put("price", price);
        data.put("nurse", nurse);
        redisCache.setCacheMapValue(APARTMENT_ROOM_PROJECT_KEY,APARTMENT_ROOM_PROJECT_HX_KEY,data);
        return data;
    }
}
